<!DOCTYPE html>
<html>
<head>
<div th:include="base-libs :: base-libs" ></div>
<title>编辑团队</title>

<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">

<style>
body {
	overflow: auto;
	background: #fff;
	margin: 0 auto;
	font-size:14px !important;
}

.h4-title{
	height:40px;
	line-height:40px;
	font-size:14px;
	background:#F7F9FB;
	margin-left:0;
	padding-left:5px;
	width:100%;
}
.spanBtn{
	font-weight: bold;
	color: blue;
	cursor:pointer;
	margin:0px 5px;
}
	.powerBtnsBox button{
		margin:auto 3px;
	}
</style>

<script>
		var tdManagerData = StoreCache.removeCache("tdManagerData");; //从index页面传过来的数据
        var tdcyUseridArr = [];   /* 成员列表userid数组 */
        var cylbTableData = {"total":0,"rows":[]};
        var oldCylbData = []; //原始成员列表
        var qtjgTableData = {"total":0,"rows":[]};
        var yTdzid = '',xTdzid='';
        var deleteTDCY = [];  //原来团队中被删除的人
        var initJgryNow = true; //是否现在马上载入机构人员？
        var isBoss = StoreCache.removeCache("isBoss");
        Array.prototype.removeByValue = function(val) {
	       	  for(var i=0; i<this.length; i++) {
	       	    if(this[i] == val) {
	       	      this.splice(i, 1);
	       	      break;
	       	    }
	       	  }
       	}
        
    	$(function(){
    		$(this).registerManagerPage();
    		initView();
    		initData();
    	})
    	
    	function initView(){
    		controlBtn();
    		
    		/* 成员列表 */
    		$("#cylbTable").datagrid({
				idField : "USERID",
				uniqueId: "USERID",
				striped : true,
				border:false,
				fitColumns: true,
				fit:true,
				clickToSelect: true,
				scrollbarSize:0, //预留的滚动条的宽度
				singleSelect:true,
				columns : [[
						{field:'XM', title:'医生姓名', width: 65, align: 'center'}
						,{field : 'SFZH',title : '身份证号', width: 110, align: 'center'}
						,{field:'SJHM', title:'手机号码', width: 80, align: 'center'}
						,{field:'YLJGMC', title:'第一执业机构', width: 100, align: 'center'}
						,{field:'TDJS', title:'团队角色', width: 50, align: 'center',formatter:function(value,row,index){
							var jsObj = {'1':'团队长','2':'普通成员','3':'团队助手'};
							return jsObj[value];
						}}
						,{field:'RTSJ', title:'入团时间', width: 50, align: 'center',formatter:function(value,row,index){
							row.RTSJ = row.RTSJ.substring(0,10);
							return value.substring(0,10);
						}}
						,{field:'USERID', title:'详细', width: 60, align: 'center',formatter:function(value,row,index){
							if($.inArray(value,tdcyUseridArr) == -1){
								tdcyUseridArr.push(value);
							}
							return '<span class="spanBtn" onclick="queryYsxx(\'' + value + '\')">医生详细</span>';
						}}
						,{field:'cz', title:'操作', width: 120, align: 'center',formatter:function(value,row,index){
				    		var TDJS = row.TDJS;
							if(TDJS==2 || TDJS==3){
                                var btns = '<span class="spanBtn" onclick="deleteCylb(\'' + row.USERID + '\')">移除成员</span>';
								row = JSON.stringify(row).replace(/"/g, '&quot;');
								if($("#qrBtn").length){
									btns += '<span class="spanBtn" onclick="changTdz(' + row + ')">设为团队长</span>';
								}
								if(TDJS==2){
									btns += '<span class="spanBtn" onclick="changeTdjs(' + row + ',3)">设为团队助手</span>';
								}else{
                                    btns += '<span class="spanBtn" onclick="changeTdjs(' + row + ',2)">设为普通成员</span>';
								}
								return btns;
							}
						}}
				]],
				method : "post",
				onBeforeLoad : function(params) {
					params["TDID"] = $("#cylbTable").data("TDID");
					if(params["TDID"]){
						return params;
					}else{
						return false;
					}
				},
				onLoadSuccess: function(data){
					cylbTableData = data;
					if(oldCylbData.length==0) {
					    //for打断数据关系
					    for(var i=0;i<data.rows.length;i++){
					        oldCylbData.push($.extend({},data.rows[i]));
						}
                    }
					$("#myBox").css("height",(data.rows.length)*37.3+83);
					$("#myLayout").layout("resize");
					if(!initJgryNow){
                        initJgryNow = true;
                        $("#btnQuery").trigger("click");
					}
 				},
			});
    		
    		/*  添加其他机构新成员 */
    		$("#qtjgTable").datagrid({
				idField : "USERID",
				uniqueId: "USERID",
				striped : true,
				border:false,
				clickToSelect: true,
				fitColumns: true,
				fit:true,
				clickToSelect: true,
				scrollbarSize:0, //预留的滚动条的宽度
				singleSelect:true,
				columns : [[
					{field:'XM', title:'医生姓名', width: 50, align: 'center'},
					{field:'XBMC', title:'性别', width: 30, align: 'center'},
					{field:'SJHM', title:'手机号码', width: 70, align: 'center'},
					{field:'YLJGMC', title:'第一执业机构', width: 90, align: 'center'},
					{field:'KSMC', title:'科室名称', width: 90, align: 'center'},
					{field:'USERID', title:'详细', width: 60, align: 'center',formatter:function(value,row,index){
//						return '<a href="javascript:void(0)" onclick=queryYsxx("'+value+'")>医生详细</a>';
                        return '<span class="spanBtn" onclick="queryYsxx(\'' + value + '\')">医生详细</span>';
					}},
					{field:'cz', title:'操作', width: 80, align: 'center',formatter:function(value,row,index){
						if($.inArray(row.USERID,tdcyUseridArr) != -1){
							return '<span>已是团队成员</span>';
						}else{
                            row = JSON.stringify(row).replace(/"/g, '&quot;');
                            return '<span class="spanBtn" onclick="addCylb(' + row + ')">加为成员</span>';
						}
					}},
				]],
				pagination : true,
				pageNumber : 1,
				pageSize : 10,
				pageList: [10, 25, 50, 100, 200, 500, 1000],
// 				url:contextRoot + "tdgl/queryYljgryxxWithConditionByPage.service",
				onBeforeLoad : function(params) {
					$(this).datagrid("resize")
	                if($("#qtjgTable").data("query")){
	                	var PTJGID = $("#YLJGMC").combogrid("getValue");
	                	if(PTJGID == parent.userInfo.YLJGMC){
	                		PTJGID = parent.userInfo.PTJGID;
	                	}
						params.PTJGID = PTJGID;
		                params.XM = $("#XM").val();
	                }else{
						return false;	                	
	                }
				},
				onLoadSuccess: function(data){
					qtjgTableData = data;
				},
			});
    		
    		$("#YLJGMC").combogrid({
    	        height: 30
    	        ,width: 200
    	        ,panelWidth: 500
    	        ,singleSelect: true
    	        ,pagination: true
    	        ,idField: 'PTJGID'
    	        ,textField: 'YLJGMC'
    	        ,mode: "remote"
    	        ,readonly: false
    	        ,hasDownArrow: true
    	        ,url: contextRoot + "/tdgl/queryYljgxxByPage.service"
    	        ,delay: 1000
    	        ,reversed: false
    	        ,columns:[[
    	            {
    	                field:'YLJGMC'
    	                ,title:'机构名称'
    	                ,width:240
    	            }
    	            ,{
    	                field:'XZQHMC'
    	                ,title:'行政区划'
    	                ,width:80
    	            }
    	            ,{
    	                field:'WSJGLBMC'
    	                ,title:'机构类别'
    	                ,width:80
    	            }
    	            ,{
    	                field:'YYDJMC'
    	                ,title:'机构等级'
    	                ,width:80
    	            }
    	        ]]
    	        ,onBeforeLoad: function(queryParams) {
    	            var url = $(this).datagrid("options")["url"];
    				//URL不等空时再发送请求
    	            if (!StringUtils.isEmpty(url)) {
    	                queryParams.YLJGMC = queryParams["q"];
    	                return true;
    	            }else{
    	                return false;
    	            }
    	        }
    	    });
    	}
    	
    	function initData(){
    		//1.载入团队基本信息
    		if(!tdManagerData){
    			tdManagerData = parent.userInfo;
    			tdManagerData.SHZT = 0;
    			tdManagerData.type = 'add';
    		}
   			tdManagerData.RTSJ = getNowDate();
   			var shztObj = {'0':'新建','2':'正常','3':'审核不通过'};
   			tdManagerData.SHZT_ = shztObj[tdManagerData.SHZT];
   			tdManagerData.YLJGMC = parent.userInfo.YLJGMC;
   			tdManagerData.SFZH = parent.userInfo.SFZH;
   			tdManagerData.LXDH = tdManagerData.LXDH || parent.userInfo.SJHM;
   			tdManagerData.XM = tdManagerData.DZXM || parent.userInfo.XM;

   			$("#tdjbxxForm [type=text]").each(function(){
   				var key = $(this).attr("name");
   				$(this).val(tdManagerData[key]);
   			})
   			$("#tdjbxxForm").data("method",tdManagerData.type);
    		if(tdManagerData.type=='add'){
    			//新增团队
    			if($("#qrBtn").length == 0){
	    			addCylb(tdManagerData,1); //将当前用户设为成员，同时兼任团队长
	    			$('#DZMC').css('color','#000');
    			}else{
    				$("#DZMC").val("");
    			}
    		}else{
    			//维护团队
	    		//2载入当前团队人员信息
	    		yTdzid = tdManagerData.USERID;
                $("#cylbTable").data("xTdzid", yTdzid);
                initJgryNow = false;
	    		$("#cylbTable").data("TDID",tdManagerData.TDID).datagrid({url : contextRoot + "tdgl/queryTdcylbAll.service"})
    		}
    		
    		
    		//3.载入本机构所有人员信息
			$("#YLJGMC").combogrid('setValue',parent.userInfo.YLJGMC);
			if(initJgryNow){
				$("#btnQuery").trigger("click");
			}
    	}
    	
        /** 添加成员列表  */
        function addCylb(userData,TDJS){
			userData.TDJS = TDJS || 2; //团队角色：默认为普通成员
			userData.RTSJ = getNowDate();
			//判断该成员是否为原团队成员
			var userId = userData.USERID;
			$.each(deleteTDCY, function(i,item){
				var delUserId = item.USERID;
				if(userId==delUserId){
					deleteTDCY.removeByValue(item);
					userData.OLD = '1';
					return false;
				}
			})
			
			cylbTableData.rows.push(userData);
			cylbTableData.total = cylbTableData.rows.length;
			
			//刷新
			$('#cylbTable').datagrid('loadData',cylbTableData);
			$('#qtjgTable').datagrid('loadData',qtjgTableData);
        }
        
        /** 移除成员列表  */
        function deleteCylb(USERID){
        	tdcyUseridArr.removeByValue(USERID);
        	for(var i=0;i<cylbTableData.rows.length;i++){
        		var item = cylbTableData.rows[i];
        		if(USERID==item.USERID){
		        	if(item.OLD){
			        	deleteTDCY.push(item);
		        	}
		        	cylbTableData.rows.removeByValue(item);
        			break;
        		}
        	}
        	//刷新
     		$('#cylbTable').datagrid('loadData',cylbTableData);
     		$('#qtjgTable').datagrid('loadData',qtjgTableData);
        }
        
        /** 修改团队长  */
        function changTdz(newTdzData){
        	$('#DZMC').css('color','#000');
        	var cylbData = cylbTableData.rows;
        	for(var i=0;i<cylbData.length;i++){
        		var item = cylbData[i];
        		if(JSON.stringify(item)==JSON.stringify(newTdzData)){
        			cylbData.removeByValue(item);
        			item.TDJS = 1;
        			cylbData.unshift(item); //将团队长移到首行
        			$("#tdjbxxForm [name=XM]").val(item.XM);
                    $("#tdjbxxForm [name=LXDH]").val(item.SJHM);
        		}
        		if(item.USERID == $("#cylbTable").data("xTdzid")){
					item.TDJS = 2;
				}
        	}
            $("#cylbTable").data("xTdzid", newTdzData.USERID);
        	$("#cylbTable").datagrid('loadData',cylbData);
        }

        /** 修改团队角色  */
        function changeTdjs(newTdzsData,TDJS){
            var cylbData = cylbTableData.rows;
            for(var i=0;i<cylbData.length;i++){
                var item = cylbData[i];
                if(JSON.stringify(item)==JSON.stringify(newTdzsData)){
                    item.TDJS = TDJS;
                    break;
                }
            }

            $("#cylbTable").datagrid('loadData',cylbData);
        }


        /** 查询医生详细 */
    	function queryYsxx(userId){
    		StoreCache.setCache("tdYsid",userId);
    		window.open(contextRoot + 'tdgl/ysInformation.html');
    	}
    	
    	/** 保存 */
    	function save(SHZT,TDZT){
    		if($(".form-control").QuickValidate()){
    			var params = getParams();
    			console.log(JSON.stringify(params))
    			params.SHZT = SHZT;
    			params.TDZT = TDZT || 0;
    			params.XJR = parent.userInfo.USERID;
    			if($("#zcBtn").length==0){
    				params.laterUpdate = 1;//后期维护
    			}
    			$.QuickRemote.AjaxFiledFormSubmit("tdjbxxForm", saveBack, params);
    		}
    		
    	}
    	
    	/** 保存回调  */
    	function saveBack(result){
    		if(result.state){
    			$.QuickAlert.alertNormal(result.info.success, {callback: function(){
        			parent.selectMenuByHand('团队列表');
        			$.QuickUrlUtils.redirectUrl("index.html");//为了当前在“团队管理”也能跳转回去
        		}});
			}else{
				var info = result["info"];
				$.QuickAlert.alertFail({content: info["faultInfo"]});
			}

    	}
    	
    	/** 获取保存的参数  */
    	function getParams(){
    		var params = {};
			
    		var addTDCY = [];
    		var changeTDCY = [];
    		$.each(cylbTableData.rows,function(i,item){
    			if(item.TDJS==1){
    				if(item.USERID == yTdzid){
	    				yTdzid=''; //没有修改团队长
    				}
   					xTdzid = item.USERID;
    			}
    			if(item.OLD){
    			    //老成员身份是否存在变化
					for(var j=0;j<oldCylbData.length;j++){
					    var oldItem = oldCylbData[j];
//					    alert("item.XM="+item.XM+"\n"+"item.USERID="+item.USERID+"\nitem.TDJS="+item.TDJS+
//								"\nitem.XM="+oldItem.XM +
//							"\nitem.USERID="+oldItem.USERID+"\nitem.TDJS="+oldItem.TDJS)
					    if(item.USERID == oldItem.USERID && item.TDJS != oldItem.TDJS){
                            changeTDCY.push({TDJS:item.TDJS,USERID:item.USERID});
					        break;
						}
					}
                    return true; //没有变化的原团队成员
    			}else{
    				addTDCY.push(item);  //新增的团队成员
    			}
    		})
    		//params.YLJGID = parent.userInfo.PTJGID;//因为可以设置任何人为团队长，所以YLJGID不一定为当前用户所在机构
    		params.CZRID = parent.userInfo.USERID;
    		params.addTDCY = JSON.stringify(addTDCY);
    		params.changeTDCY = JSON.stringify(changeTDCY); //修改过的团员
    		params.deleteTDCY = JSON.stringify(deleteTDCY);
    		params.yTdzid = yTdzid; //原团队长id
    		params.xTdzid = xTdzid; //现团队长id
    		params.method = $("#tdjbxxForm").data("method");
    		params.TDID = tdManagerData.TDID || "";
    		
    		return params;
    	}
    	
    	/** 查询其他机构人员信息 */
    	function btnQueryQtjgry(){
    		$("#qtjgTable").data("query",true).datagrid({url:contextRoot + "tdgl/queryYljgryxxWithConditionByPage.service"})
    	}
    	
    	/** 获取当前日期  */
    	function getNowDate(){
			var date = new Date();
		    var month = date.getMonth() + 1
		    if(month<10) month = "0" + month;
		    var day = date.getDate();
		    if(day<10) day = "0" + day;
		    return ""+date.getFullYear()+"-"+month+"-"+day;
		};
		
		function controlBtn(){
			//删除用户没有的权限按钮
        	$(".powerBtnsBox button").each(function(){
        		var btnId = $(this).attr("id");
        		if(powerBtns.indexOf(btnId) == -1){
        			$(this).remove();
        		}
        	})
    		//返回按钮的选择性删除
    		var forbackUrl = StoreCache.removeCache('forbackUrl');
    		if(StringUtils.isEmpty(forbackUrl)){
    			$("#fhBtn").remove();
    		}else{
    			$("#fhBtn").on("click",function(){
    				StoreCache.setCache("tdManagerData", tdManagerData);
    				if(forbackUrl=="detail.html"){
                    	StoreCache.setCache("isBoss",isBoss);
					}
                    $.QuickUrlUtils.redirectUrl(forbackUrl);
    			})
    		}
    		
    		//医院管理员正在维护正常团队
    		if(isBoss && tdManagerData.SHZT == 2){
    			$("#zcBtn").remove();
    		}
		}
		
		
</script>
</head>

<body>

<div class="easyui-layout" fit="true">
<div  region="center" border="false">
	<div style="height:170px;overflow:hidden;"> <!-- border:1px solid #ddd;border-radius:4px; -->
		<div  class="easyui-layout" fit="true" border="false" style="height:170px">
			<div region="center" border="false" style="overflow:hidden">
				<!-- <div class="title">团队基本信息</div> -->
				<h4 class="h4-title">
				团队基本信息
				</h4>
				<form id="tdjbxxForm" action="save">
						<table class="form-table">
							<tr>
								<td class="td-text">
									<label>团队名称</label>
								</td>
								<td><input id="TDMC" type="text" class="form-control check" name="TDMC"
									placeholder="团队名称" 
									quick-config="label:'团队名称', validateProxy:'notNull length', length: '100'" />
								</td>
								<td class="td-text">
									<label>团队状态</label>
								</td>
								<td><input type="text" disabled="disabled" style="color:#000" 
									class="form-control" name="SHZT_" /></td>
								<td class="td-text">
									<label>所属医疗机构</label>
								</td>
								<td><input type="text" disabled="disabled" style="color:#000" 
									class="form-control" name="YLJGMC" /></td>
							</tr>
							<tr>
								<td class="td-text">
									<label>团队队长</label>
								</td>
								<td>
									<input type="text" class="form-control" name="XM" placeholder="团队队长" id="DZMC" disabled="disabled"
										quick-config="label:'团队队长', validateProxy:'notNull'" style="color:#000"/>
								</td>
								<td class="td-text">
									<label>手机号码</label>
								</td>
								<td><input type="text" class="form-control" name="LXDH"
									placeholder="手机号码"
									quick-config="label:'手机号码', validateProxy:'notNull length num', length: '11'" />
								</td>
								<td class="td-text">
									<label>创建时间</label>
								</td>
								<td><input type="text" disabled="disabled" style="color:#000" 
									class="form-control" name="RTSJ" /></td>
							</tr>
							<tr>
								<td class="td-text">
									<label>联系地址</label>
								</td>
								<td><input type="text" class="form-control" name="LXDZ"
									placeholder="联系地址"
									quick-config="label:'联系地址', validateProxy:'notNull length', length: '200'" />
								</td>
								<td class="td-text">
									<label>团队简介</label>
								</td>
								<td colspan="3"><input type="text" class="form-control"
									name="TDJJ" placeholder="团队简介"
									quick-config="label:'团队简介', validateProxy:'length', length: '200'" style="width:96%"/>
								</td>
							</tr>
						</table>
					</form>
			</div>
		</div>
	</div>
		
	<div id="myBox" style="margin-top: 5px;height:90px;width:100%;overflow:hidden">
		<div  class="easyui-layout" border="false" fit="true" id="myLayout">
			<div region="north" style="overflow:hidden;height:40px;" border="false">
				<!-- <div class="title">成员列表</div> -->
				<h4 class="h4-title">成员列表</h4>
			</div>
			<div region="center" border="false" fit="true">	
				<table id="cylbTable"></table>
			</div>
		</div>
	</div>
	
	<div style="height:540px;margin-top: 8px;">
		<div  class="easyui-layout" fit="true" border="false">
			<div region="north" style="height:90px;overflow:hidden" border="false">
				<!-- <div class="title">添加新成员</div> -->
				<h4 class="h4-title">添加新成员</h4>
				<table class="form-table" id="qtyljgForm">
						<tr>
							<td class="td-text" style="width:100px">第一执业机构名称</td>
							<td style="width:265px;">
								<input type="text" placeholder="" class="form-control" id="YLJGMC"/>
							</td>
							<td class="td-text">医生姓名</td>
							<td>
								<input type="text" placeholder="" class="form-control" id="XM"/>
							</td>
							<td>
								<button id="btnQuery" class="btn btn-default" type="button" onclick="btnQueryQtjgry()">查询</button>
							</td>
						</tr>
				</table>
			</div>
			<div region="center" border="false">
				<table id="qtjgTable" fit="true"></table>
			</div>
		</div>
	</div>
</div>


<!-- 固定按钮区域 -->
<div region="south" class="powerBtnsBox"  border="false" style="height:55px;line-height:55px;text-align:center;overflow:hidden;border-top:1px solid #ddd">
		  <button type="button" onclick="save(0)" id="zcBtn">暂存</button>
		  <button type="button" onclick="save(1)" id="tjshBtn">提交审核</button>
		  <button type="button" onclick="save(2,1)" id="qrBtn">确认</button>
		  <button type="button"  id="fhBtn">返回</button>
</div>
</div>
</body>
</html>
